#include "missionselection.h"
#include "ui_missionselection.h"

#include <QDateTime>
#include <QMessageBox>

#include "common/data.h"
#include "common/database.h"
#include "common/tool.h"

MissionSelection::MissionSelection(QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::MissionSelection)
{
    ui->setupUi(this);

    connect(ui->btnSelect, &QPushButton::clicked, this, &MissionSelection::jump);
    connect(ui->lineSearch, &QLineEdit::textChanged, this, &MissionSelection::search);
    connect(ui->comboModel, &QComboBox::currentTextChanged, this, &MissionSelection::search);

    Database::loadMissions();
    Tool::setTableHeaders(ui->tableMission,
                          {"ID",
                           "任务代号",
                           "任务标志",
                           "火箭型号",
                           "坐标系",
                           "通信方式",
                           "发射点",
                           "发射方位角",
                           "发射时间"});
    ui->tableMission->hideColumn(0);
    for (const auto& mission : Data::missions)
    {
        Tool::appendTableRow(ui->tableMission,
                             {
                                 QString::number(mission.id),
                                 mission.code,
                                 mission.mark,
                                 mission.rocketModel,
                                 mission.coordinate,
                                 mission.method,
                                 mission.launchPoint,
                                 QString::number(mission.launchAzimuth),
                                 mission.launchTime.toString(Tool::DATETIME_FORMAT),
                             });
    }

    for (int i = 0; i < Data::missions.size(); ++i)
    {
        if (ui->comboModel->findText(Data::missions[i].rocketModel) == -1)
        {
            ui->comboModel->addItem(Data::missions[i].rocketModel);
        }
    }
}

MissionSelection::~MissionSelection()
{
    delete ui;
}

void MissionSelection::search()
{
    QString line = ui->lineSearch->text();
    QString combo = ui->comboModel->currentText();
    for (int r = 0; r < ui->tableMission->rowCount(); ++r)
    {
        ui->tableMission->setRowHidden(r,
                                       (ui->tableMission->item(r, COL_CODE)->text().contains(line, Qt::CaseInsensitive) == false) || (combo != "全部" && ui->tableMission->item(r, COL_ROCKET_MODEL)->text() != combo));
    }
}

void MissionSelection::jump()
{
    if (ui->tableMission->currentRow() == -1)
    {
        QMessageBox::warning(this, "温馨提示", "请选择一个任务");
        return;
    }

    int currentRow = ui->tableMission->currentRow();
    Data::currentMissionId = ui->tableMission->item(currentRow, 0)->text().toInt();
    emit selected(currentRow);
}
